import { Component, OnInit } from '@angular/core';
import { GridOptions } from '@ag-grid-community/core';
import { GridConfigService } from '@core/config/grid-config.service';
import { ExportExcelService } from '@core/services/excel/export-excel.service';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { PurchaseService } from '../purchase.service';
import { UserAuthService } from '@core/services/user-auth.service';
import { catchError, debounceTime, distinctUntilChanged, map, switchMap, tap } from 'rxjs/operators';
import { fillField, missing } from '../../../../utils/utils';
import { of } from 'rxjs/internal/observable/of';
import { Subject } from 'rxjs/internal/Subject';
import { AllModules, Module } from '@ag-grid-enterprise/all-modules';

@Component({
  selector: 'purchase-billing',
  templateUrl: './purchase-billing.component.html',
  styleUrls: ['../purchase-report-form.scss'],
})
export class PurchaseBillingComponent implements OnInit {
  /* 按钮相关 */
  buttonBar = [
    { hide: true, style: 'default', label: '导出', id: 'action_export' },
    { hide: true, style: 'default', label: '查询', id: 'action_query', loading: false },
    { hide: true, style: 'default', label: '重置', id: 'action_reset' },
    // { hide: true, style: 'default', label: '展开查询条件', id: 'action_show' },
  ];
  title = '';
  ctx = { model: {} };
  showMoreBtn = true;
  showData = true;

  /** Grid 相关 **/
  public modules: Module[] = AllModules;
  rowData: any;
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  rowClassRules: any;
  height: any = window.innerHeight - 285 + 'px';

  // 报错样式
  // hind: string = 'none';
  show: string = 'none';           // 展开查询条件
  days: any;

  // 获取门店、询价区域、销售组、供应商
  store: any;
  inquiry: any;
  sale: any;
  supplier: any;

  mdjcTime: any = [];       // 日期
  startValue: Date = null;
  endValue: Date = null;
  storeID: string;                    // 门店
  inquiryID: any;                     // 询价区域
  saleID: any[];                      // 销售组
  supplierID: string;                 // 供应商
  carNum: string;                     // 车牌号
  checkOne: boolean = true;          // 未报价
  checkTwo: boolean = false;         // 已超时
  checkThree: boolean = false;       // 未询价要货
  userInfo = this.userAuthService.getUserInfoObj();
  companyId = this.userInfo.userAccount.post.company.id;
  permitId = this.userInfo.userAccount.post.localPermit.id;
  companyData: any;
  companyList: any[] = [];
  companyClone: any[] = [];
  productData: any;
  productList: any;
  contractinput$ = new Subject<string>();
  contractLoading = false;
  searchSelectApi: string = 'cm.product.findAll';
  private _searchText = '';
  private _current = 0;
  private _size = 20;
  private _pages = 0;
  _domain: any = {
    'filters': [
      {
        'field': 'id',
        'operator': 'EQ',
        'value': '{{value}}',
      },
      {
        'field': 'name',
        'operator': 'LIKE',
        'value': '{{value}}',
      },
    ],
    'groups': [],
    'operator': 'or',
  };
  formState;


  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private exportExcelService: ExportExcelService,
              private msg: ApesMessageService,
              private pa: PurchaseService,
              private userAuthService: UserAuthService) {
    this.gridInit();
    this.loadContract();
  }

  ngOnInit() {
    this.initialization();
  }

  // gird初始化
  gridInit() {
    this.columnDefs = [
      { 'headerName': '车牌', field: 'CPHM', width: 110, pinned: 'left' },
      { 'headerName': '门店', field: 'MDMC', width: 150 },
      { 'headerName': '要货单号', field: 'YHDH', width: 120 },
      { 'headerName': '商品编码', field: 'SPID' },
      { 'headerName': '商品名称', field: 'SPMC' },
      { 'headerName': '要货时间', field: 'SHRQ_SJ' },
      { 'headerName': '耗时', field: 'HS', cellRenderer: this.pa.toHour },
      { 'headerName': '超时', field: 'TIO', cellRenderer: this.pa.toHour },
      { 'headerName': '询价区域', field: 'XJQY' },
      { 'headerName': '销售组', field: 'XSZMC' },
      { 'headerName': '供应商编码', field: 'GYSID' },
      { 'headerName': '供应商名称', field: 'GYSMC' },
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 100,
      rowHeight: 35,
    };
    this.gridOptions.localeText = this.gridConfigService.getLocaleText();
    this.rowClassRules = {
      // 预警
      'grid-tab-breach': function(params) {
        let now = params.data.TIO;
        return now < 0;
      },
      // 超时
      'grid-tab-warning': function(params) {
        let now = params.data.TIO;
        return now >= 0;
      },
    };
  }

  // 初始化
  initialization() {
    this.pa.getCompany(this.permitId).then(value => {
      this.companyData = value;
      this.companyClone = this.companyData.map(item => {
        return item.id;
      });
      this.queryData();
    });
    this.pa.getSaleData().then(value => {
      this.sale = value;
    });
    this.pa.getInquiryData().then(value => {
      this.inquiry = value;
    });
    this.pa.getSupplierData().then(value => {
      this.supplier = value;
    });
  }

  onEvent(data: any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[1].loading = true;
        this.queryData();
        this.show = 'none';
      } else if (data.id === 'action_reset') {
        this.action_reset();
      } else if (data.id === 'action_export') {
        this.action_export();
      } else if (data.id === 'action_show') {
        // this.action_show();
      }
    }
  }

  // 导出数据
  action_export() {
    if (this.rowData && this.rowData.length === 0) {
      return;
    }
    for (let i = 0, len = this.rowData.length; i < len; i++) {
      this.rowData[i]['HS'] = this.pa.toHour(this.rowData[i]['HS']);
      this.rowData[i]['TIO'] = this.pa.toHour(this.rowData[i]['TIO']);
    }
    const columnList = this.gridOptions.columnDefs;
    this.exportExcelService.exportWithDealData(columnList, this.rowData, '采购开单监控报表');
  }

  // 重置
  action_reset(): void {
    this.mdjcTime = '';
    this.storeID = '';
    this.inquiryID = '';
    this.saleID = [];
    this.supplierID = '';
    this.carNum = '';
    this.checkOne = true;
    this.checkTwo = false;
    this.checkThree = false;
    this.companyList = [];
    this.productList = [];
  }

  // 展开查询条件
  action_showMore() {
    if (this.showData) {
      // this.showMore(true);
      this.showData = false;
    } else {
      // this.showMore(false);
      this.showData = true;
    }
  }

  // 查询按钮事件
  queryData() {
    let list = [];
    if (this.companyList.length <= 0) {
      list = this.companyClone;
    } else {
      list = this.companyList;
    }
    this.rowData = [];
    this.pa.getDate(this.mdjcTime, 'startValue', 'endValue', this);
    let SPID = this.productList? this.productList['id'] : null;
    const data = {
      'interfaceMethod': 'ipmPurchareControlReportService.queryReplenishment', 'pdata': {
        'START_TYRQ_SJ': this.startValue,
        'END_TYRQ_SJ': this.endValue,
        'XJQY': this.inquiryID,
        'CPHM': this.carNum,
        'MDID': this.storeID,
        'GYSID': this.supplierID,
        'TYBJ': this.checkOne,
        'YCSBJ': this.checkTwo,
        'FXJYH': this.checkThree,
        'XSZID': this.saleID,
        'SPID': SPID,
        'companyId': list,
      },
    };
    this.pa.getTablesData(data).then(value => {
      this.rowData = value;
    });
    this.pa.getStoreData(this.companyList).then(value => {
      this.store = value;
    });
    this.buttonBar[1].loading = false;
  }

  private loadContract() {
    this.contractinput$.pipe(
      debounceTime(500),
      distinctUntilChanged(),
      tap(() => this.contractLoading = true),
      switchMap((term) => {
        if (missing(term)) {
          this.contractLoading = false;
          return of([]);
        }
        if ( this._searchText === term) return of([]);
        this._current = 0;
        this._searchText = term;
        const data = this.getApiParams();
        return this.apiService.post(this.searchSelectApi, data).pipe(
          map((res) => {
              this.productData = [];
              this._searchText = term;
              this.productData = this.productData.concat(res.content);
              this._current = res.page + 1;
              this._pages = res.pages;
              return res.content;
            }
          ),
          catchError(() => of([])), // empty list on error
          tap(() => this.contractLoading = false)
        ); })
    ).subscribe();
  }

  getApiParams() {
    const data = {key: this._searchText, page: this._current, size: this._size};
    if (this._domain) {
      const group = fillField(this._domain, this.formState,false, this._searchText);
      data['group'] = group;
    }
    return data;
  }

}
